<template>
	<div class="app-container">
		<div ref="box3" class="flex-center margin-bottom-10">
			<el-radio-group
				v-model="searchParams.auditState"
				class="item-gap"
				@change="onStateChange"
			>
				<el-radio-button
					v-for="(item, index) in stateList"
					:key="index"
					:label="item.id"
				>
					<el-badge
						v-if="item.count"
						:value="item.count"
						:max="99"
					>
						<span class="margin-right-20">{{ item.name }}</span>
					</el-badge>
					<span v-else class="margin-right-10">{{ item.name }}</span>
				</el-radio-button>
			</el-radio-group>
		</div>
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-add-button
						:permission-prefix="prefix"
						class="margin-5-0 item-gap"
						@click="onAddBtn"
					></jk-add-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-date-picker
						v-model="searchParams.belongDates"
						clearable
						size="small"
						type="daterange"
						start-placeholder="派工日期"
						end-placeholder="派工日期"
						class="search-bar-item-size4 item-gap"
					></jk-date-picker>
					<jk-select
						v-model="searchParams.upkeepTypeId"
						:clearable="true"
						:option-list="upkeepTypeList"
						placeholder="保养类别"
						class="search-bar-item-size1 margin-5-0 item-gap"
					></jk-select>
					<jk-search-input
						v-model="searchParams.code"
						:clearable="true"
						placeholder="派工单号"
						class="search-bar-item-size3 margin-5-0 item-gap"
						@on-enter="onSearchBtn"
					></jk-search-input>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="jkTable"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 10"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-state-bar
							v-if="item.keyName === 'auditState'"
							:state="scope.row.auditState"
							:state-list="stateList"
						></jk-state-bar>
						<span
							v-else-if="item.keyName === 'upkeepTypeList'"
						>{{ scope.row.upkeepTypeList ? scope.row.upkeepTypeList.map(x => x.name).join() : '' }}</span>
						<span v-else-if="item.keyName === 'code'">
							<i v-if="searchParams.auditState === 1 ? false : belongTimeValue > getCompletionTime(scope.row.planCompletionTime)" style="font-size: 20px" color="#fac324" class="el-icon-warning"></i>
							{{ scope.row.code }}
						</span>
						<div
							v-else-if="item.keyName === 'machineList'"
							class="link-style"
							@click="onMachineListBtn(scope.row)"
						>{{ scope.row.machineList ? scope.row.machineList.map(x => x.machineName).join('、') : '' }}</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="260">
					<template slot-scope="scope">
						<div class="flex-center">
							<!--<jk-button
								:has-permission="getPermission([`${prefix}:update`])"
								size="mini"
								type="success"
								class="item-gap"
								:icon="!scope.row.auditState ? 'el-icon-check' : 'el-icon-close'"
								@click="onToggleStateBtn(scope.row)"
							>{{ !scope.row.auditState ? '完成' : '撤销' }}</jk-button>-->
							<jk-button
								:has-permission="getPermission([`${prefix}:update`])"
								:disabled="scope.row.auditState === 1"
								class="item-gap"
								size="mini"
								icon="el-icon-edit"
								type="primary"
								@click="onEditBtn(scope.row)"
							>编辑</jk-button>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.auditState !== item.allowState : false"
										:style="{
											'display': !item.isShow ? 'none' : 'block',
											'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through'
										}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:page-type="pageType"
			:data-id="dataId"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
		<updateStateDialog
			:data-id="dataId"
			:dialog-state="updateStateDialogState"
			@on-visible-change="onVisibleChangeOfUpdateStateDialogState"
			@on-update="onFinishOfUpdateStateDialogState"
		></updateStateDialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar, formatTime } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import handlerCache from '../../../../mixins/handler-cache';
    import upkeepMixin from '../upkeepItemPlan/upkeep';
    import {
        machineManagerUpkeepDispatchDelete,
        machineManagerUpkeepDispatchPage, machineManagerUpkeepDispatchPlanBatchUpdateStateFinish
    } from '../../../../api/machine/upkeepOrder';
    import { machineManagerUpkeepTypePage } from '../../../../api/machine/upkeepCategory';
    import permissionMixin from '../../../../mixins/permission-mixin';
    import updateStateDialog from './update-state-dialog';
    export default {
        name: 'UpkeepOrder',
        components: {
            updateStateDialog,
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache, upkeepMixin, permissionMixin],
        data() {
            return {
                prefix: 'machinemanager:upkeepDispatch',
                updateStateDialogState: false,
                apiItem: {
                    'page': machineManagerUpkeepDispatchPage
                },
                stateList: [
                    { id: 0, name: '未完成', color: '#ff9900' },
                    { id: 1, name: '已完成', color: '#2d8cf0' },
                    { id: -1, name: '全部', color: '#0bab5b' }
                ],
                dropdownOption: [
                    { code: 'DETAIL', name: '详情', permissionName: 'query', isShow: true, icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'DELETE', name: '删除', permissionName: 'delete', isShow: true, icon: 'el-icon-delete', allowState: 0, api: machineManagerUpkeepDispatchDelete }
                ],
                dataId: null,
                saveDialogState: false,
                tableLoading: true,
                tableData: [],
                upkeepTypeList: [],
                totalCount: 0,
                searchParams: {
                    pageNo: 1,
                    pageSize: pageConfig.pageSize,
                    belongDates: [],
                    upkeepTypeId: null,
                    auditState: 0,
                    processId: null
                },
                pageType: '',
                belongTimeValue: ''
            };
        },
        methods: {
            getCompletionTime(data) {
                console.log('new Date(data).getTime()', data, new Date(data).getTime());
                return new Date(data).getTime();
            },
            onStateChange() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onFinishOfUpdateStateDialogState() {
                this.getListRequest();
            },
            onVisibleChangeOfUpdateStateDialogState(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.updateStateDialogState = e;
            },
            onMachineListBtn(row) {
                this.dataId = row.id;
                this.updateStateDialogState = true;
            },
            onDropdownChange(type, { id }) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (optionItem) {
                    if (optionItem.code === 'DETAIL') {
                        this.onDetailBtn({ id });
                    } else {
                        this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                            optionItem.api({ id: id }).then(res => {
                                if (res.data.status === 200) {
                                    this.getListRequest();
                                }
                            });
                        }).catch(() => {});
                    }
                }
            },
            onToggleStateBtn(row) {
                this.$msgbox({
                    title: '消息',
                    message: `确认 "${!row.auditState ? '完成' : '撤销'}" ？`,
                    iconClass: 'el-icon-question',
                    showCancelButton: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '执行中...';
                            machineManagerUpkeepDispatchPlanBatchUpdateStateFinish({ ids: [this.scope.row.id] }).then(res => {
                                instance.confirmButtonLoading = false;
                                instance.confirmButtonText = '确定';
                                if (res.data.status === 200) {
                                    tipsBar(this, 'save');
                                    this.getListRequest();
                                    done();
                                }
                            });
                        } else {
                            done();
                        }
                    }
                });
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.pageType = 'detail';
                this.saveDialogState = true;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.saveDialogState = e;
            },
            getStateBarCountRequest() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.auditState = 0;
                this.stateList.forEach(x => {
                    if (x.id === 0) {
                        this.$set(x, 'count', 0);
                    }
                });
                return this.apiItem.page(params).then(res => {
                    if (res.data.status === 200) {
                        this.stateList.forEach(x => {
                            if (x.id === 0) {
                                this.$set(x, 'count', res.data.count);
                            }
                        });
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                if (params.auditState === -1) params.auditState = null;
                this.getStateBarCountRequest();
                this.apiItem.page(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res || [];
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.pageType = 'add';
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.pageType = 'edit';
                this.dataId = row.id;
                this.saveDialogState = true;
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getUpkeepTypeListRequest() {
                return machineManagerUpkeepTypePage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.upkeepTypeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.belongTimeValue = new Date(formatTime(Date.now())).getTime();
                await this.getMenuColumnListRequest();
                await this.getUpkeepTypeListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
